import React, { useState, useRef, useEffect } from 'react';
import styled from '@emotion/styled';

interface ColorPickerProps {
  value?: string;
  onChange?: (color: string) => void;
  disabled?: boolean;
  className?: string;
  placeholder?: string;
}

export type { ColorPickerProps };

const ColorPickerContainer = styled.div`
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  position: relative;
`;

const ColorDisplay = styled.div<{ color?: string; disabled?: boolean }>`
  width: 40px;
  height: 40px;
  border-radius: 6px;
  border: 2px solid var(--border-color, #e5e7eb);
  background: ${(props) => props.color || '#ffffff'};
  cursor: ${(props) => (props.disabled ? 'not-allowed' : 'pointer')};
  opacity: ${(props) => (props.disabled ? 0.5 : 1)};
  transition: all 0.2s ease;
  position: relative;

  &:hover {
    border-color: ${(props) => !props.disabled && 'var(--accent-color, #3b82f6)'};
  }

  /* 显示无颜色时的斜线 */
  ${(props) =>
    !props.color &&
    `
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 2px;
      background: var(--error-color, #ef4444);
      transform: translateY(-50%) rotate(-45deg);
    }
  `}
`;

const HiddenInput = styled.input`
  position: absolute;
  opacity: 0;
  pointer-events: none;
  width: 0;
  height: 0;
`;

const StyledInput = styled.input<{ error?: boolean }>`
  flex: 1;
  padding: 0.625rem 0.75rem;
  border: 1px solid ${(props) => (props.error ? 'var(--error-color, #ef4444)' : 'var(--border-color, #e5e7eb)')};
  border-radius: 8px;
  background: var(--bg-secondary, #f9fafb);
  color: var(--text-primary, #111827);
  font-size: 0.875rem;
  font-family: 'Consolas', 'Monaco', monospace;
  line-height: 1.5;
  transition: all 0.2s ease;
  outline: none;

  &:hover {
    border-color: ${(props) => (props.error ? 'var(--error-color, #ef4444)' : 'var(--accent-color, #3b82f6)')};
  }

  &:focus {
    border-color: ${(props) => (props.error ? 'var(--error-color, #ef4444)' : 'var(--accent-color, #3b82f6)')};
    background: var(--bg-primary, #ffffff);
    box-shadow: 0 0 0 3px
      ${(props) =>
        props.error
          ? 'rgba(239, 68, 68, 0.1)'
          : 'var(--accent-color-shadow, rgba(59, 130, 246, 0.1))'};
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background: var(--bg-tertiary, #f3f4f6);
  }

  &::placeholder {
    color: var(--text-tertiary, #9ca3af);
  }
`;

export const ColorPicker: React.FC<ColorPickerProps> = ({
  value = '',
  onChange,
  disabled = false,
  className,
  placeholder = '#000000',
}) => {
  const [inputValue, setInputValue] = useState(value);
  const [isValid, setIsValid] = useState(true);
  const inputRef = useRef<HTMLInputElement>(null);
  const colorInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setInputValue(value);
  }, [value]);

  const validateColor = (color: string): boolean => {
    if (!color) return true;
    // 验证十六进制颜色格式
    const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    return hexRegex.test(color);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    setInputValue(newValue);

    const valid = validateColor(newValue);
    setIsValid(valid);

    if (valid && onChange) {
      onChange(newValue);
    }
  };

  const handleColorClick = () => {
    if (!disabled && colorInputRef.current) {
      colorInputRef.current.click();
    }
  };

  const handleColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newColor = e.target.value;
    setInputValue(newColor);
    setIsValid(true);
    if (onChange) {
      onChange(newColor);
    }
  };

  return (
    <ColorPickerContainer className={className}>
      <ColorDisplay color={isValid ? inputValue : undefined} disabled={disabled} onClick={handleColorClick} />
      <HiddenInput
        ref={colorInputRef}
        type="color"
        value={inputValue || '#000000'}
        onChange={handleColorChange}
        disabled={disabled}
      />
      <StyledInput
        ref={inputRef}
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder={placeholder}
        disabled={disabled}
        error={!isValid}
      />
    </ColorPickerContainer>
  );
};

export default ColorPicker;

